package cn.daniellee.plugin.wc.storage;

import cn.daniellee.plugin.wc.Welcome;
import cn.daniellee.plugin.wc.model.PlayerData;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.Set;

public class SqliteStorage extends Storage {

	private Connection connection;

	@Override
	public boolean initialize() {
		// 初始化Sqlite驱动
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while getting the Sqlite database driver.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
			return false;
		}
		// 初始化连接
		String url = "jdbc:sqlite:" + Welcome.getInstance().getDataFolder() + "/" + "storage.db";
		try {
			connection = DriverManager.getConnection(url);
		} catch (Exception e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]Sqlite connection information is incorrect.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
			return false;
		}
		// 初始化数据表
		String playerSql = "CREATE TABLE IF NOT EXISTS `player` (" +
				"`name` TEXT(48) NOT NULL," +
				"`join_date` integer(20)," +
				"PRIMARY KEY (`name`)" +
				");";
		String playerIndexSql = "CREATE UNIQUE INDEX IF NOT EXISTS `index_name` ON `player` (`name`);";
		try(Statement statement = connection.createStatement()) {
			statement.execute(playerSql);
			statement.execute(playerIndexSql);
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while initializing the Sqlite player table.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
			return false;
		}
		// 初始化Welcomed表
		String welcomedSql = "CREATE TABLE IF NOT EXISTS `welcomed` (" +
				"  `name` TEXT(48) NOT NULL," +
				"  `welcomer` TEXT(48) NOT NULL" +
				");";
		String welcomedIndexSql = "CREATE INDEX IF NOT EXISTS `index_name` ON `welcomed` (`name`);";
		try(Statement statement = connection.createStatement()) {
			statement.execute(welcomedSql);
			statement.execute(welcomedIndexSql);
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while initializing the Sqlite welcomed table.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
			return false;
		}
		return true;
	}

	@Override
	public Connection getConnection() {
		return connection;
	}

	@Override
	public PlayerData getPlayerDataByName(String name) {
		PlayerData playerData = null;
		String sql = " SELECT `name`,`join_date` FROM `player` WHERE `name` = ?";
		try (PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, name);
			ResultSet resultSet = statement.executeQuery();
			if (resultSet.next()) {
				playerData = new PlayerData(name);
				playerData.setJoinDate(resultSet.getLong("join_date"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while reading building data from Sqlite.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
		}
		return playerData;
	}

	@Override
	public void addPlayerData(PlayerData playerData) {
		PreparedStatement statement = null;
		try {
			String sql = "INSERT INTO `player` (`name`,`join_date`)VALUES(?,?)";
			statement = connection.prepareStatement(sql);
			statement.setString(1, playerData.getName());
			statement.setLong(2, playerData.getJoinDate());
			statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while writing building data to Sqlite.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
		} finally {
			if (statement != null) {
				try {
					statement.close();
				} catch (SQLException ignored) { }
			}
		}
	}


	@Override
	public boolean checkWelcomed(String welcomee, String welcomer) {
		String sql = " SELECT `name`,`welcomer` FROM `welcomed` WHERE `name` = ? AND `welcomer` = ?";
		try (PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, welcomee);
			statement.setString(2, welcomer);
			ResultSet resultSet = statement.executeQuery();
			return resultSet.next();
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while reading building data from Sqlite.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
		}
		// 默认返回True，避免出错时一直欢迎成功
		return true;
	}

	@Override
	public void addWelcomed(String welcomee, String welcomer) {
		String sql = "INSERT INTO `welcomed` (`name`,`welcomer`)VALUES(?,?)";
		try(PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, welcomee);
			statement.setString(2, welcomer);
			statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while writing building data to Sqlite.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
		}
	}

	@Override
	public void close() {
		try {
			connection.close();
		} catch (SQLException ignored) { }
	}
}
